import { defineStore } from 'pinia';
import { auth, fetchChangePassword, getMe } from 'src/services/userService';
import { Dialog } from 'quasar';
import ls from '../stores/storage';
const KEY = 'cews_user';

export const useUser = defineStore('userStore', {
  state: () => ({
    token: '',
    user_id:0,
    is_superuser:false,
    username: ''
  }),
  getters: {
    isLogin: (state) => state.token != undefined && state.token != '',
  },
  actions: {
    async login(username: string, password: string) {
      try {
        const res = await auth(username, password);
        console.log(res);
        
        // eslint-disable-next-line no-unsafe-optional-chaining
        const { token } = res?.data;
        this.token = token;
        const meRes = await getMe()
        console.log(meRes);
        
        this.user_id = meRes.data.id
        this.is_superuser = meRes.data.is_superuser
        this.username = meRes.data.username
        this.save();

        return true;
      } catch (err) {
        console.log('Login fail');
        return false;
      }
    },
    save() {
      ls.set(
        KEY,
        JSON.stringify({
          token: this.token,
          user_id:this.user_id,
          username: this.username,
          is_superuser: this.is_superuser
        })
      );
    },
    load() {
      const res = ls.get(KEY);      
      if (!res) {
        this.logout()
      };
      try {
        const data = JSON.parse(res);
        console.log(data);
        
        if (data) {
          this.token = data.token;
          this.user_id = data.user_id
          this.username = data.username
          this.is_superuser = data.is_superuser
        }
      } catch (err) {
        console.log(err);
      }
    },
    logout(){
      ls.remove(KEY)
      this.token = ''
      this.user_id=0
      this.username = ''
      this.is_superuser = false
    },
    async changePassword(old_password: string, new_password: string, confirm_new_password:string) {

        const res = await fetchChangePassword(old_password, new_password, confirm_new_password);
        return res.data;
     
    },
  },
});
